package gui.actions;

import gui.models.ConfigurationModel;
import gui.panels.configurations.EntryPanel.EntryMode;

import javax.swing.JComponent;
import javax.swing.JOptionPane;

import common.Fictionator;
import common.interfaces.ConfigurationsInterface;

public class ConfigurationAction extends WorkerAction {

	private static final long serialVersionUID = 1L;
	private final ConfigurationModel model;
	private final EntryMode mode;
	private ConfigurationsInterface configurationsLogic;
	private boolean actionResult;

	public ConfigurationAction(JComponent owner, ConfigurationModel model, EntryMode mode) {
		super(owner);
		this.model = model;
		this.mode = mode;
		configurationsLogic = Fictionator.getInstance().getConfigurationsLogic();
	}
	
	@Override
	public boolean isAllowToRunOperation() {
		return true;
	}
	
	@Override
	public void runOperation() throws Exception {
		switch (mode) {
		case New:
			actionResult = configurationsLogic.createCharacter(model.getSelectedCharacter());
			break;
		case Edit:
			actionResult = configurationsLogic.updateCharacter(model.getSelectedCharacter());
			break;
		case Delete:
			actionResult = configurationsLogic.removeCharacter(model.getSelectedCharacter());
			break;
		}
	}
	
	@Override
	public void operationSucceed() {
		if (!actionResult) {
			String errorMsg;
			String errorTitle;
			switch (mode) {
			case New:
				errorTitle = "Create character failed";
				errorMsg = "The given character is already exist in the database.\nThe operation didn't take affect.";
				break;
			case Edit:
				errorTitle = "Change character failed";
				errorMsg = "The given character wasn't found in the database.\nThe operation didn't take affect.";
				break;
			case Delete:
			default:
				errorTitle = "Delete character failed";
				errorMsg = "The given character wasn't found in the database.\nThe operation didn't take affect.";
			}
			JOptionPane.showMessageDialog(getOwner(), errorMsg, errorTitle, JOptionPane.ERROR_MESSAGE);
		} else {
		    switch (mode) {
		    case New:
		        break;
		    case Edit:
		        break;
		    case Delete:
		    default:
		        model.getCharacters().remove(model.getSelectedCharacter());
		        if (model.getCharacters().isEmpty()) {
		            model.createNewCharacter();
		        } else {
		            model.setSelectedCharacter(model.getCharacters().get(0));
		        }
		        model.setSearchResultsSize(model.getSearchResultsSize()-1);
		        model.notifyObservers();
		    }
		}
	}
	
	@Override
	public void operationFailed(Exception e) {
		String errorMsg = "An error in database operation occured.\nThe following error occured: " + e.getLocalizedMessage() + "\nThe operation didn't take affect";
		String errorTitle = "Database operation failed";
		JOptionPane.showMessageDialog(getOwner(), errorMsg, errorTitle, JOptionPane.ERROR_MESSAGE);
	}

}
